package com.archives.blog.manager.impl;

import com.archives.blog.manager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.archives.blog.common.domain.dao.AdminRepository;
import com.archives.blog.common.domain.entity.Admin;
import com.archives.blog.common.domain.pojo.request.AdminLoginRequest;
import com.archives.blog.common.domain.pojo.request.AdminQueryRequest;
import com.archives.blog.common.enums.ErrorCodeEnum;
import com.archives.blog.common.exp.BlogException;
import com.archives.blog.common.utils.MD5Util;

@Service
public class AdminManagerImpl implements AdminManager {
	
	@Autowired
	private AdminRepository adminRepository;
	
	public static void main(String[] args) {
		System.out.println(MD5Util.MD5("123456"));
	}
	
	@Override
	public Admin login(AdminLoginRequest request) {
		Admin admin = getByUserName(request.getLoginName());
		
		if (admin == null) {
			throw new BlogException(ErrorCodeEnum.PARAM_ILLEGAL, "登录名不存在");
		}
		if (!MD5Util.MD5(request.getPassword()).equals(admin.getPassword())) {
			throw new BlogException(ErrorCodeEnum.PARAM_ILLEGAL, "登录名、密码不匹配");
		}
		
		return admin;
	}
	
	public Admin getByUserName(String userName){
		return adminRepository.findByUserName(userName);
	}
	
	@Override
	public Page<Admin> getPage(AdminQueryRequest request) {
		Pageable pageable = new PageRequest(request.getPageIndex(), request.getPageSize());
		Admin probe = new Admin();
		probe.setUserName(request.getUserName());
		Example<Admin> example = Example.of(probe);
		Page<Admin> page = adminRepository.findAll(example, pageable);
		return page;
	}
}
